package service

import (
	"time"

	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

const (
	dateFormat     = "2006-01-02"
	maxDateRange  = 365 // 最大日期范围（天）
	defaultPage    = 1
	defaultPageSize = 10
	maxPageSize    = 100
)

// validateAndParseDates 验证并解析日期参数
func validateAndParseDates(startDateStr, endDateStr string) (time.Time, time.Time, error) {
	if startDateStr == "" || endDateStr == "" {
		return time.Time{}, time.Time{}, status.Errorf(codes.InvalidArgument, "start_date and end_date are required")
	}

	startDate, err := time.Parse(dateFormat, startDateStr)
	if err != nil {
		return time.Time{}, time.Time{}, status.Errorf(codes.InvalidArgument, "invalid start_date format, should be YYYY-MM-DD")
	}

	endDate, err := time.Parse(dateFormat, endDateStr)
	if err != nil {
		return time.Time{}, time.Time{}, status.Errorf(codes.InvalidArgument, "invalid end_date format, should be YYYY-MM-DD")
	}

	if startDate.After(endDate) {
		return time.Time{}, time.Time{}, status.Errorf(codes.InvalidArgument, "start_date cannot be after end_date")
	}

	// 验证日期范围
	if endDate.Sub(startDate).Hours() > maxDateRange*24 {
		return time.Time{}, time.Time{}, status.Errorf(codes.InvalidArgument, "date range cannot exceed %d days", maxDateRange)
	}

	return startDate, endDate, nil
}

// normalizePagination 规范化分页参数
func normalizePagination(page, pageSize int32) (int, int) {
	p := int(page)
	if p < 1 {
		p = defaultPage
	}

	ps := int(pageSize)
	if ps < 1 {
		ps = defaultPageSize
	} else if ps > maxPageSize {
		ps = maxPageSize
	}

	return p, ps
}

